package com.keda.springdata_elasticsearch.utils;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import com.keda.springdata_elasticsearch.config.LogConfigPropertires;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;

@Component
@Slf4j
public class EsUtil {

    @Autowired(required = false)
    private ElasticsearchClient elasticsearchClient;

    @Autowired
    private LogConfigPropertires propertires;

    @Autowired
    private ResourceLoader resourceLoader;
    public CreateIndexResponse buildIndex(String indexName, String mappingFilePath) {
        try {
            // 1、判断目标索引是否存在
            boolean flag = elasticsearchClient.indices().exists(builder -> builder.index(indexName)).value();
            if (flag) {
                // 目标索引已存在
                log.info("索引【" + propertires.getEs().getIndexName() + "】已存在！");
                return null;
            }
            // 1. 获取【创建索引请求对象】
            CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder()
                    .index(indexName)
                    .mappings(TypeMapping.of(builder -> builder.withJson(getMappingReader(mappingFilePath))))
                    .build();
            // 2. 创建索引，得到【创建索引响应对象】
            CreateIndexResponse createIndexResponse = elasticsearchClient.indices().create(createIndexRequest);
            boolean result = createIndexResponse.acknowledged();
            if (result) {
                log.info("索引【" + indexName + "】创建成功！");
            } else {
                log.info("索引【" + indexName + "】创建失败！");
            }
            return createIndexResponse;
        } catch (Exception e) {
            log.error("创建索引失败", e);
        }
        return null;
    }
    private Reader getMappingReader(String jsonFilePath) {
        Reader reader = null;
        String jsonContent = null;
        try {
            Resource resource = resourceLoader.getResource("classpath:" + jsonFilePath);
            if (resource.exists()) {
                BufferedReader breader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
                StringBuilder content = new StringBuilder();
                String line;
                while ((line = breader.readLine()) != null) {
                    content.append(line);
                }
                jsonContent = content.toString();
                reader = new StringReader(jsonContent);
            } else {
                log.error("Elasticsearch-json文件未找到 {}",jsonFilePath);
            }
        } catch (Exception ioException) {
            log.error("Elasticsearch-json文件读取异常 {}",jsonFilePath);
        }
        return reader;
    }
}
